<template>
  <div class="w-full h-full p-3 rounded-xl border-slate-200 bg-white">
    <div class="flex items-center  content-center  mb-2">
      <div class="flex items-center bg-indigo-50/60 rounded-lg py-0.5 px-2">
        <i class="iconfont icon-shishikucunshiyitu text-indigo-500 text-base"/>
        <span class="title font-semibold text-indigo-600 ml-1.5">{{ $t('inventoryInforSummary.rawMaterial') }}</span>
      </div>
      <div class="flex-1 h-[1px] bg-gradient-to-r from-indigo-200 via-indigo-100/50 to-transparent ml-3"></div>
      <el-form :inline="true" :model="from" class="align-center search-form" style="margin-bottom: 10px">
        <el-form-item class="label" :label="$t('iot.time')">
          <el-date-picker
            style="width: 220px" v-model="from.time" type="daterange"
            range-separator="-" :start-placeholder="$t('wms.startTime')" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
            :end-placeholder="$t('wms.endTime')" class="custom-date-picker"/>
        </el-form-item>
        <el-button icon="Search" class="buttons" size="small" type="primary" @click="getSerch" style="margin-top: 3px">
          {{ $t('wms.search') }}
        </el-button>
      </el-form>

    </div>
    <div class="w-full flex items-center mt-4" style="height: 1%;text-align: center">
      <div class="w-full h-full" style="border-radius: 16px;" v-if="!headerList.length">
        <el-empty  :description="$t('inventoryInforSummary.allocateDataFor')"/>
      </div>
      <div class="table-list w-full h-full" v-else>
        <el-table
          ref="tableRef" border id="out-table" :data="headerList" :fit="true" table-layout="fixed"
          max-height="430"
          header-align="center" style="width:100%;" :header-cell-style="{
          color: '#1e293b',textAlign: 'center',fontWeight: '600',
          background: 'linear-gradient(to bottom, #f8fafc, #f1f5f9)',borderColor: '#e2e8f0',height: '40px'}"
          :cell-style="{textAlign: 'center',color: '#334155',borderColor: '#e2e8f0',background: '#fff',height: '40px'}">
          <el-table-column prop="materialType" :label="$t('common.materialType')">
            <template #header>
              <span class="flex items-center justify-center w-full">
                {{ $t('common.materialType') }}
                <span class="text-indigo-500 ml-2 text-sm">({{ headerList.length }})</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="sourceWarehouName" :label="$t('common.OutWarehouse')" >
            <template #default="scope">
              <el-button-group size="">
                <el-button type="info w-[80px]" class="">{{scope.row.sourceWarehouName}}</el-button>
                <el-button type="info w-[80px]"  class="" plain>{{scope.row.sourceWarehouCode}}</el-button>
              </el-button-group>
            </template> <template #default="scope">
            <el-button-group size="">
              <el-button type="info w-[80px]" class="">{{scope.row.sourceWarehouName}}</el-button>
              <el-button type="info w-[80px]"  class="" plain>{{scope.row.sourceWarehouCode}}</el-button>
            </el-button-group>
          </template>
          </el-table-column>
          <el-table-column prop="targetWarehouName" :label="$t('common.InWarehouse')" >
            <template #default="scope">
              <el-button-group size="">
                <el-button type="primary w-[80px]" class="">{{scope.row.targetWarehouName}}</el-button>
                <el-button type="primary w-[80px]"  class="" plain>{{scope.row.targetWarehouCode}}</el-button>
              </el-button-group>
            </template>
          </el-table-column>
          <el-table-column prop="qty" :label="$t('mes.qty')" width="120">
            <template #default="scope">
              <el-tag type="warning" size="large"  class="w-[90px]" plain>{{scope.row.qty}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="unit" :label="$t('wms.unit')" width="80">
            <template #default="scope">
              <el-tag type="info" size="large" class="w-[60px]" plain effect="">{{scope.row.unit}}</el-tag>
            </template>
          </el-table-column>
        </el-table>
        <!-- <div class="flex justify-end mt-3">
          <el-pagination :current-page="data.page" :page-size="5"
                         :page-sizes="[10, 20, 50, 100]" small background class="custom-pagination"
                         :total="data.headerTotal" @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"/>
        </div> -->
      </div>
    </div>
  </div>
</template>
<script setup>
import '@/assets/font/iconfont.css'
import { getRawMaterialsTransferSummary } from '@/api/mes/allocationInforViewApi'
import useI18n from '@/hooks/language'
import { onMounted, reactive,ref, onUnmounted } from 'vue'
import moment from 'moment'
import router from '@/router'

const { t } = useI18n()
const data = reactive({
  current: 1,
  size: 20,
  headerTotal:0
})
const from = reactive({
  time: [],
})

const headerList = ref([])
const tableRef = ref(null)
let scrollTimer = null
let isUserInteracting = false
let lastScrollPosition = 0

const startScroll = () => {
  if (scrollTimer) {
    clearInterval(scrollTimer)
  }
  scrollTimer = setInterval(() => {
    const table = tableRef.value
    if (table && !isUserInteracting) {
      const scrollWrapper = table.$el.querySelector('.el-scrollbar__wrap')
      if (scrollWrapper) {
        if (scrollWrapper.scrollTop + scrollWrapper.clientHeight >= scrollWrapper.scrollHeight) {
          // 到达底部，暂停3秒
          clearInterval(scrollTimer)
          setTimeout(() => {
            scrollWrapper.scrollTop = 0
            startScroll()
          }, 3000)
        } else {
          scrollWrapper.scrollTop += 1
        }
      }
    }
  }, 50)
}

const stopScroll = () => {
  if (scrollTimer) {
    clearInterval(scrollTimer)
    scrollTimer = null
  }
}

const handleUserInteraction = () => {
  isUserInteracting = true
  const table = tableRef.value
  if (table) {
    const scrollWrapper = table.$el.querySelector('.el-scrollbar__wrap')
    if (scrollWrapper) {
      lastScrollPosition = scrollWrapper.scrollTop
    }
  }
  stopScroll()
}

const resumeScroll = () => {
  isUserInteracting = false
  const table = tableRef.value
  if (table) {
    const scrollWrapper = table.$el.querySelector('.el-scrollbar__wrap')
    if (scrollWrapper) {
      scrollWrapper.scrollTop = lastScrollPosition
    }
  }
  startScroll()
}

const getDefaultDateRange = () => {
  const start = moment().subtract(0, 'days').format('YYYY-MM-DD')// 本月一号
  const end = moment().format('YYYY-MM-DD') // 今天
  from.time = [start, end]
}

onMounted(async () => {
  await getDefaultDateRange()
  await rawMaterialsTransferSummary()
  startScroll()

  // 添加用户交互事件监听
  const table = tableRef.value
  if (table) {
    const scrollWrapper = table.$el.querySelector('.el-scrollbar__wrap')
    if (scrollWrapper) {
      scrollWrapper.addEventListener('mousedown', handleUserInteraction)
      scrollWrapper.addEventListener('touchstart', handleUserInteraction)
      scrollWrapper.addEventListener('mouseup', resumeScroll)
      scrollWrapper.addEventListener('touchend', resumeScroll)
      scrollWrapper.addEventListener('wheel', handleUserInteraction)
    }
  }
})

onUnmounted(() => {
  stopScroll()
  // 移除事件监听
  const table = tableRef.value
  if (table) {
    const scrollWrapper = table.$el.querySelector('.el-scrollbar__wrap')
    if (scrollWrapper) {
      scrollWrapper.removeEventListener('mousedown', handleUserInteraction)
      scrollWrapper.removeEventListener('touchstart', handleUserInteraction)
      scrollWrapper.removeEventListener('mouseup', resumeScroll)
      scrollWrapper.removeEventListener('touchend', resumeScroll)
      scrollWrapper.removeEventListener('wheel', handleUserInteraction)
    }
  }
})

const rawMaterialsTransferSummary = async () => {
  await getRawMaterialsTransferSummary({
    startTime: from.time[0],
    endTime: from.time[1],
    current: data.current,
    size: data.size
  }).then(res => {
    if (res.code == 0) {
      headerList.value = res.data.records
      data.headerTotal= res.data.total
    }
  })
}


const handleSizeChange = (val) => {
  data.size = val
  rawMaterialsTransferSummary()
}

const handleCurrentChange = (val) => {
  data.current = val
  rawMaterialsTransferSummary()
}

const getSerch = () => {
  rawMaterialsTransferSummary()
}
const goBack =() =>{
  router.push('/transferQuantity');
}
</script>
<style scoped lang="scss">

</style>
